import axios from "axios";
import 'dotenv/config';
import { getTenantAccessToken } from "./certificate";

const {
    FEISHU_API_URL: feishuApi,
    FEISHU_APP_TOKEN: appToken,
    FEISHU_TABLE_USER: table_user,
    FEISHU_TABLE_ACTIVITY: table_activity,
} = process.env;

export enum FeiShuTable {
    User = "user",
    Activity = "activity",
}

const FeiShuTableId = {
    [FeiShuTable.User]: table_user,
    [FeiShuTable.Activity]: table_activity,
};

const API = (tableId: string) => `${feishuApi}/bitable/v1/apps/${appToken}/tables/${tableId}/records`

export async function saveTableRecords(
    table: FeiShuTable,
    record: { [key: string]: any }
) {
    const tableId = FeiShuTableId[table] || '';
    const {
        data: { msg, code, data },
    } = await axios.post(
        `${API(tableId)}`,
        { fields: record },
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );

    if (code != 0) throw Error(msg);
    return { id: data.record.id, ...data.record.fields };
}

export async function getTableRecords(
    table: FeiShuTable,
    urlParam: string,
    id?: string
) {
    const tableId = FeiShuTableId[table] || '';

    const url = !!id ? `${API(tableId)}/${id}` : `${API(tableId)}?${urlParam}`

    const {
        data: { msg, code, data }
    } = await axios.get(
        `${url}`,
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );

    if (code != 0) throw Error(msg);

    const results: any[] = [];

    if (data["total"] > 0) {
        const items = data["items"];
        for (const item of items) {
            results.push({ id: item.id, ...item.fields })
        }
        return results;
    }

    if (!!id) return { id: data.record.id, ...data.record.fields }

    return {}
}


export async function updateTableRecords(
    table: FeiShuTable,
    record: { [key: string]: any },
    recordId: string
) {
    const tableId = FeiShuTableId[table] || '';
    const {
        data: { msg, code, data }
    } = await axios.put(
        `${API(tableId)}/${recordId}`,
        { fields: record },
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );

    if (code != 0) throw Error(msg);
    return data;
}